package cn.itcast.gateway.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class GateWayAuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1-解析请求头里面的参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        String auth = queryParams.getFirst("auth");

        // 2-判断参数是否是amin
        if (StringUtils.equals("admin", auth)) {
            // 2.1 是，放行
            return chain.filter(exchange);
        }

        // 2.2 不是，拦截并返回异常信息
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

}
